package com.gbq.utils;

import lombok.Data;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;



@Data
// FTP工具类提供链接和上传功能
public class FTPUtil {

	public static FTPClient ftp;

	public FTPUtil() {

	}

	public static boolean connect(String path, String addr, int port, String username, String password)
			throws Exception {
		boolean result = false;
		ftp = new FTPClient();
		int reply;
		ftp.connect(addr, port);
		
		ftp.setControlEncoding("GBK");
        FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
        conf.setServerLanguageCode("zh");
		
		ftp.login(username, password);
		//ftp.setControlEncoding("UTF-8");
		ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

		reply = ftp.getReplyCode();
		if (!FTPReply.isPositiveCompletion(reply)) {
			ftp.disconnect();
			return result;
		}
		result = ftp.changeWorkingDirectory(path);
		result = true;
		return result;
	}

	/**
	 * 上传文件
	 * 
	 * @param pathname
	 *            本地服务器文件目录
	 * @param filename
	 *            文件名称
	 * @return t.connect("\\test\\22", "10.5.202.100", 21, "admin", "111111");
	 *         t.upload("c:\\","test");
	 *         因为远程链接的根目录为文件夹22，所以运行结果为上传本地服务器根目录下的test文件夹到远端ftp的文件夹22目录下
	 */
	public static boolean upload(String pathname, String filename) throws Exception {

		boolean result = false;
		File file = new File(pathname + "/" + filename);
		// System.out.println("upload is starting...");

		if (file.isDirectory()) {
			ftp.makeDirectory(file.getName());
			ftp.changeWorkingDirectory(file.getName());
			String[] files = file.list();

			for (int i = 0; i < files.length; i++) {

				// System.out.println(file.getPath()+"\\"+files[i]);
				File file1 = new File(file.getPath() + "/" + files[i]);
				if (file1.isDirectory()) {
					upload(file.getPath(), files[i]);
					ftp.changeToParentDirectory();
				} else {

					System.out.println(file.getPath() + "/" + files[i]);
					File file2 = new File(file.getPath() + "/" + files[i]);
					FileInputStream input = new FileInputStream(file2);
					ftp.storeFile(file2.getName(), input);
					input.close();
				}
			}

		} else {

			String filePath = file.getPath();
			File file2 = new File(filePath);
			FileInputStream input = new FileInputStream(file2);
			String file2Name = file2.getName();
			ftp.storeFile(file2Name, input);
			input.close();
		}

		result = true;
		return result;
	}

	public static boolean stop(){

		try {
			ftp.disconnect();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}

	}

}
